// /src/pages/userCenter/Marathon.jsx
import { useState, useEffect } from 'react';
import { 
  Tabs, 
  List, 
  Card, 
  Tag, 
  Badge, 
  Spin, 
  Empty, 
  Alert,
  Button,
  Modal 
} from 'antd';
import { 
  ClockCircleOutlined, 
  TrophyOutlined,
  CrownOutlined,
  DashboardOutlined,
  PieChartOutlined,
  QuestionCircleOutlined
} from '@ant-design/icons';
import { 
  useNavigate, 
  useLocation,
  Outlet 
} from 'react-router-dom';
import { userAPI } from '@/api/user';
import './marathon.styl';
import { 
    PieChart, 
    Pie, 
    Cell ,
    Tooltip, // 添加这行
    Legend // 添加这行
  } from 'recharts';

const { TabPane } = Tabs;

// 帮助内容（润色后）
const HELP_CONTENT = `
保种马拉松活动规则

连续30天为指定种子保种，可领取限定徽章+魔力值礼包。系统将自动记录您的保种时长，并在达到要求时自动发放奖励。

指定种子类型：
1. **新上传资源** - 站内近期发布的资源
2. **濒危资源** - 保种数量少、下载速度慢的资源

奖励规则：
- 🥉 连续保种7天：青铜守卫者徽章 + 500魔力值
- 🥈 连续保种15天：白银捍卫者徽章 + 1000魔力值
- 💎 连续保种30天：钻石永恒者徽章 + 3000魔力值

> 系统每天自动检查您的保种状态，达标后奖励将在24小时内发放。
`;

// 虚拟数据
const mockMarathons = [
  {
    id: 1,
    torrentId: 1,
    torrentName: "测试种子",
    marathonType: "new_resource",
    consecutiveDays: 15,
    startDate: "2024-05-10T00:00:00",
    lastSeedingDate: "2024-05-26T23:07:43",
    status: "active",
    earnedBadges: ["bronze_guard","silver_defender"],
    createdAt: "2024-05-26T22:16:55"
  }
];

const mockBadges = [
  {
    id: 1,
    badgeType: "bronze_guard",
    badgeName: "青铜守卫者",
    description: "连续7天保种获得青铜守卫者徽章",
    magicReward: 500,
    earnedAt: "2024-05-26T22:16:55"
  }
];

const mockStats = {
  activeMarathons: 2,
  completedMarathons: 0,
  badgeStatistics: {
    "青铜守卫者": 2,
    "白银捍卫者": 1,
    "钻石永恒者": 0
  }
};

// 徽章配置
const BADGE_CONFIG = {
  bronze_guard: { 
    color: '#cd7f32', 
    icon: <TrophyOutlined style={{ fontSize: 20 }} />,
    label: "青铜守卫者"
  },
  silver_defender: { 
    color: '#c0c0c0', 
    icon: <TrophyOutlined style={{ fontSize: 20 }} />,
    label: "白银捍卫者"
  },
  diamond_eternal: { 
    color: '#1890ff', 
    icon: <CrownOutlined style={{ fontSize: 20 }} />,
    label: "钻石永恒者"
  }
};

// 马拉松类型映射
const MARATHON_TYPE_MAP = {
  new_resource: { name: '新资源', color: 'blue' },
  endangered: { name: '濒危资源', color: 'red' },
  default: { name: '其他类型', color: 'gray' }
};

// 保种记录组件
const MarathonRecords = () => {
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [data, setData] = useState([]);
  const [isHelpVisible, setIsHelpVisible] = useState(false);

  useEffect(() => {
    const loadData = async () => {
      try {
        const res = await userAPI.getMyMarathons();
        setData(res.data?.data || mockMarathons);
      } catch (error) {
        console.error('获取数据失败', error);
        setData(mockMarathons);
        setError('数据加载失败，显示模拟数据');
      } finally {
        setLoading(false);
      }
    };
    loadData();
  }, []);
  return (
      <>
        <Card
            title={<><ClockCircleOutlined /> 进行中的挑战</>}
            extra={
              <Button
                  type="link"
                  icon={<QuestionCircleOutlined />}
                  onClick={() => setIsHelpVisible(true)}
              >
                帮助说明
              </Button>
            }
        >
          <Spin spinning={loading}>
            {error && <Alert message={error} type="warning" showIcon className="mb-16" />}
            <List
                itemLayout="vertical"
                dataSource={data}
                renderItem={item => {
                  // 安全获取类型配置，添加错误处理
                  const typeConfig = MARATHON_TYPE_MAP[item.marathonType] || MARATHON_TYPE_MAP.default;

                  return (
                      <List.Item
                          className="marathon-item"
                          extra={
                            <div className="status-panel">
                              <Tag color={item.status === 'active' ? 'green' : 'gray'}>
                                {item.status === 'active' ? '进行中' : '已结束'}
                              </Tag>
                              <div className="days">
                                <span className="number">{item.consecutiveDays}</span>
                                <span className="unit">天</span>
                              </div>
                            </div>
                          }
                      >
                        <List.Item.Meta
                            title={<a href={`/torrent/${item.torrentId}`}>{item.torrentName}</a>}
                            description={<>
                              <Tag color={typeConfig.color}>
                                {typeConfig.name}
                              </Tag>
                              <span className="time">开始于 {new Date(item.startDate).toLocaleDateString()}</span>
                            </>}
                        />
                        <div className="badges">
                          {item.earnedBadges.map(badge => (
                              <Badge
                                  key={badge}
                                  className="badge-item"
                                  count={BADGE_CONFIG[badge]?.icon}
                                  style={{ backgroundColor: BADGE_CONFIG[badge]?.color }}
                              />
                          ))}
                        </div>
                      </List.Item>
                  );
                }}
                locale={{ emptyText: <Empty description="暂无保种记录" /> }}
            />
          </Spin>
        </Card>

      <Modal
        title="保种马拉松帮助"
        visible={isHelpVisible}
        onCancel={() => setIsHelpVisible(false)}
        footer={
          <Button type="primary" onClick={() => setIsHelpVisible(false)}>
            我知道了
          </Button>
        }
        width={650}
      >
        <div style={{
          padding: '16px 0',
          fontSize: 14,
          lineHeight: 1.8
        }}>
          <pre style={{
            fontFamily: 'inherit',
            whiteSpace: 'pre-wrap',
            margin: 0
          }}>
            {HELP_CONTENT}
          </pre>
        </div>
      </Modal>
    </>
  );
};

// 徽章收藏组件
const BadgeCollection = () => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(true);
  const [data, setData] = useState([]);

  useEffect(() => {
    const loadData = async () => {
      try {
        const res = await userAPI.getMyBadges();
        setData(res.data?.data || mockBadges);
      } catch (error) {
        console.error('获取数据失败', error);
        setData(mockBadges);
      } finally {
        setLoading(false);
      }
    };
    loadData();
  }, []);

  return (
    <Card 
      title={<><TrophyOutlined /> 我的徽章</>}
    >
      <Spin spinning={loading}>
        <div className="badge-grid">
          {data.map(badge => (
            <div key={badge.id} className="badge-card">
              <div 
                className="badge-icon"
                style={{ backgroundColor: BADGE_CONFIG[badge.badgeType]?.color }}
              >
                {BADGE_CONFIG[badge.badgeType]?.icon}
              </div>
              <h3>{badge.badgeName}</h3>
              <p>{badge.description}</p>
              <Tag color="gold">+{badge.magicReward}魔力值</Tag>
              <div className="earned-time">
                获得时间: {new Date(badge.earnedAt).toLocaleDateString()}
              </div>
            </div>
          ))}
          {data.length === 0 && <Empty description="暂无已获得徽章" />}
        </div>

        <div className="mobile-stats-entry">
          <Button 
            block 
            type="primary"
            icon={<PieChartOutlined />}
            onClick={() => navigate('/user/stats')}
          >
            查看完整统计
          </Button>
        </div>
      </Spin>
    </Card>
  );
};

// 统计图表组件
const MarathonStats = () => {
    const [loading, setLoading] = useState(true);
    const [statsData, setStatsData] = useState(mockStats);
    const COLORS = ['#0088FE', '#00C49F', '#FFBB28', '#FF8042'];
  
    useEffect(() => {
      const loadData = async () => {
        try {
          const res = await userAPI.getMarathonStats();
          setStatsData(res.data?.data || mockStats);
        } catch (error) {
          console.error('获取统计失败', error);
          setStatsData(mockStats);
        } finally {
          setLoading(false);
        }
      };
      loadData();
    }, []);
  
    const badgeChartData = Object.entries(statsData.badgeStatistics || {})
      .map(([name, value]) => ({ name, value }));
  
    const CustomTooltip = ({ active, payload }) => {
      if (active && payload?.[0]) {
        return (
          <div className="custom-tooltip">
            <p className="label">{payload[0].payload.name}</p>
            <p className="value">获得次数: {payload[0].value}</p>
          </div>
        );
      }
      return null;
    };
  
    return (
      <Card
        title={
          <div className="stats-header">
            <DashboardOutlined />
            <span>保种统计</span>
          </div>
        }
      >
        <Spin spinning={loading}>
          <div className="stats-container">
            <div className="quick-stats">
              <div className="stat-card">
                <div className="stat-value">{statsData.activeMarathons}</div>
                <div className="stat-label">进行中的挑战</div>
              </div>
              <div className="stat-card">
                <div className="stat-value">{statsData.completedMarathons}</div>
                <div className="stat-label">已完成挑战</div>
              </div>
            </div>
  
            <div className="chart-container">
              <PieChart width={730} height={300}>
                <Pie
                  data={badgeChartData}
                  cx="50%"
                  cy="50%"
                  innerRadius={60}
                  outerRadius={100}
                  paddingAngle={5}
                  dataKey="value"
                  nameKey="name"
                >
                  {badgeChartData.map((entry, index) => (
                    <Cell 
                      key={`cell-${index}`}
                      fill={COLORS[index % COLORS.length]}
                    />
                  ))}
                </Pie>
                <Tooltip 
                  content={<CustomTooltip />}
                  wrapperStyle={{ 
                    backgroundColor: '#fff',
                    padding: '8px 12px',
                    borderRadius: '4px',
                    boxShadow: '0 2px 8px rgba(0,0,0,0.15)'
                  }}
                />
                <Legend 
                  layout="vertical"
                  align="right"
                  verticalAlign="middle"
                  wrapperStyle={{ 
                    right: 0,
                    paddingLeft: '20px'
                  }}
                  formatter={(value) => (
                    <span style={{ color: '#666', fontSize: '12px' }}>
                      {value}
                    </span>
                  )}
                />
              </PieChart>
            </div>
  
            <div className="data-notes">
              <Tag color="geekblue">数据更新周期：每小时自动更新</Tag>
              <Tag color="green">统计时间范围：全部历史记录</Tag>
            </div>
          </div>
        </Spin>
      </Card>
    );
  };

export default function MarathonPage() {
    const navigate = useNavigate();
    const location = useLocation();
  
    // 根据路径自动激活对应标签
    const getActiveKey = () => {
      if (location.pathname.includes('stats')) return 'stats'
      if (location.pathname.includes('badges')) return 'badges'
      return 'records'
    }
  
    return (
      <div className="marathon-page">
        <Tabs
          activeKey={getActiveKey()}
          onChange={key => navigate(`/user/marathons/${key}`)}
        >
          <TabPane
            key="records"
            tab={<span><ClockCircleOutlined />进行中的挑战</span>}
          >
            <Outlet />
          </TabPane>
          <TabPane
            key="badges"
            tab={<span><TrophyOutlined />徽章收藏</span>}
          >
            <Outlet />
          </TabPane>
          {/* 新增统计标签页 */}
          <TabPane
            key="stats"
            tab={<span><DashboardOutlined />保种统计</span>}
          >
            <MarathonStats />
          </TabPane>
        </Tabs>
      </div>
    );
  }

export { MarathonRecords, BadgeCollection, MarathonStats };